<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小圆助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 动画效果 */
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }

        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 6px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        /* 输入框光标效果 */
        .input-cursor {
            display: inline-block;
            width: 2px;
            height: 20px;
            background: #3b82f6;
            animation: blink 1s infinite;
            vertical-align: middle;
            margin-left: 2px;
        }

        /* 消息气泡尾巴 */
        .message-bubble {
            position: relative;
            border-radius: 18px 18px 18px 4px;
        }

        .message-bubble::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: -8px;
            width: 16px;
            height: 16px;
            background: white;
            border-radius: 0 0 12px 0;
            clip-path: polygon(0 0, 100% 0, 100% 100%);
        }

        .user-message .message-bubble {
            border-radius: 18px 18px 4px 18px;
            background: #3b82f6;
        }

        .user-message .message-bubble::after {
            left: auto;
            right: -8px;
            background: #3b82f6;
            border-radius: 0 0 0 12px;
            clip-path: polygon(0 0, 0 100%, 100% 0);
        }

        /* 加载动画 */
        .loading-dots {
            display: inline-flex;
            gap: 4px;
        }

        .loading-dots span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #94a3b8;
            animation: bounce 1.4s infinite ease-in-out;
        }

        .loading-dots span:nth-child(2) {
            animation-delay: 0.2s;
        }

        .loading-dots span:nth-child(3) {
            animation-delay: 0.4s;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen flex items-center justify-center p-4">
<div class="bg-white rounded-2xl shadow-xl overflow-hidden w-full max-w-[420px] flex flex-col h-[600px]">
    <!-- 助手头部 -->
    <div class="bg-gradient-to-r from-blue-500 to-indigo-600 p-5 flex items-center">
        <div class="relative">
            <div class="w-14 h-14 rounded-full bg-white flex items-center justify-center shadow-lg animate-bounce">
                <i class="fas fa-robot text-2xl text-blue-500"></i>
            </div>
            <div class="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white"></div>
        </div>
        <div class="ml-4">
            <h2 class="text-xl font-bold text-white">小圆助手</h2>
            <p class="text-blue-100 text-sm">在线为您服务</p>
        </div>
    </div>

    <!-- 对话区域 -->
    <div class="flex-1 p-4 overflow-y-auto" id="chatContainer">
        <!-- 欢迎消息 -->
        <div class="flex justify-center mb-6">
            <div class="bg-blue-100 text-blue-800 px-4 py-2 rounded-full text-sm animate-fadeIn">
                <i class="fas fa-sparkles mr-2"></i>你好！我是小圆，有什么问题问我吧~
            </div>
        </div>

        <!-- 消息将在这里动态添加 -->
    </div>

    <!-- 输入区域 -->
    <div class="border-t border-gray-100 p-4 bg-gray-50">
        <div class="flex gap-2">
            <input type="text" id="userInput"
                   class="flex-1 px-4 py-2.5 border border-gray-200 rounded-full focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
                   placeholder="输入您的问题..."
                   autocomplete="off">
            <button id="submitBtn"
                    class="bg-blue-500 hover:bg-blue-600 text-white w-12 h-12 rounded-full flex items-center justify-center shadow-md transition-all">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>
</div>

<script>
    const chatContainer = document.getElementById('chatContainer');
    const userInput = document.getElementById('userInput');
    const submitBtn = document.getElementById('submitBtn');
    let isProcessing = false;

    // 添加用户消息
    function addUserMessage(message) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex justify-end mb-4 animate-fadeIn';
        messageDiv.innerHTML = `
                <div class="max-w-[75%]">
                    <div class="user-message">
                        <div class="message-bubble py-3 px-4 text-white">
                            ${message}
                        </div>
                    </div>
                </div>
            `;
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 添加助手消息（加载中）
    function addAssistantTyping() {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex mb-4 animate-fadeIn';
        messageDiv.innerHTML = `
                <div class="max-w-[75%]">
                    <div class="flex items-end gap-2">
                        <div class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center animate-pulse">
                            <i class="fas fa-robot text-gray-400 text-sm"></i>
                        </div>
                        <div class="message-bubble bg-white py-3 px-4 shadow-sm">
                            <div class="loading-dots">
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
        return messageDiv;
    }

    // 更新助手消息（完成）
    function updateAssistantMessage(element, message) {
        element.innerHTML = `
                <div class="max-w-[75%]">
                    <div class="flex items-end gap-2">
                        <div class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center">
                            <i class="fas fa-robot text-blue-500 text-sm"></i>
                        </div>
                        <div class="message-bubble bg-white py-3 px-4 shadow-sm">
                            ${message}
                        </div>
                    </div>
                </div>
            `;
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 流式消息处理
    async function streamResponse(question, loadingElement) {
        try {
            const response = await fetch(`http://localhost:8080/ai_rolephay/stream?question=${encodeURIComponent(question)}`, {
                headers: { 'Accept': 'text/event-stream' }
            });

            if (!response.ok) throw new Error('请求失败');

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullMessage = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value).replace('data', '');
                if (chunk.trim()) {
                    fullMessage += chunk;
                    updateAssistantMessage(loadingElement, fullMessage);
                }
            }
        } catch (error) {
            console.error('Error:', error);
            updateAssistantMessage(loadingElement, '抱歉，我遇到了一点问题，请再问我一次吧~');
        } finally {
            isProcessing = false;
        }
    }

    // 发送消息
    async function sendMessage() {
        const question = userInput.value.trim();
        if (!question || isProcessing) return;

        isProcessing = true;
        userInput.value = '';

        // 添加用户消息
        addUserMessage(question);

        // 添加助手加载中状态
        const loadingElement = addAssistantTyping();

        // 流式获取响应
        await streamResponse(question, loadingElement);
    }

    // 事件监听
    submitBtn.addEventListener('click', sendMessage);

    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendMessage();
    });

    // 输入框聚焦效果
    userInput.addEventListener('focus', () => {
        submitBtn.classList.add('bg-blue-600');
    });

    userInput.addEventListener('blur', () => {
        if (!isProcessing) {
            submitBtn.classList.remove('bg-blue-600');
        }
    });
</script>
</body>
</html>